package dao;

import java.sql.*;

import utilClasses.ListaPrevoznika;
import utilClasses.uPrevoznik;




public class daoPrevoznik {

	public static void kreirajPrevoznika( String naziv, String telefon, String email, String web) throws SQLException {
		Connection c = daoKonekcija.dajKonekciju();
	CallableStatement cStmt = c.prepareCall("{CALL Insert_prevoznik(?,?,?,?)}");
	cStmt.setString(1, naziv);
	cStmt.setString(2, telefon);
	cStmt.setString(3, email);
	cStmt.setString(4, web);
	cStmt.execute();
	
	System.out.println("Uspjesno unesen prevoznik!\n");
	cStmt.close();
	c.close();
	}

	
	public static ListaPrevoznika dajPrevoznike() throws SQLException
	{
		Connection c = daoKonekcija.dajKonekciju();
		ListaPrevoznika rez=new ListaPrevoznika();
		String iskaz = "SELECT * FROM prevoznik";
		try {
			Statement stmt = c.createStatement();
			ResultSet rs=stmt.executeQuery(iskaz);
			while (rs.next()) {
		    	String naziv=rs.getString(2);
		    	String telefon=rs.getString(3);
		    	String email= rs.getString(4);
		    	String web=rs.getString(5);
		        rez.getPrevoznici().add(new uPrevoznik(naziv,telefon,email,web)); 
		        }
		  rs.close();  
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		c.close();
		return rez;
		}
	
	static int dajidPrevoznika(String naziv) throws SQLException
	{
		Connection c = daoKonekcija.dajKonekciju();
		PreparedStatement ps=c.prepareStatement("SELECT idprevoznik FROM prevoznik WHERE Naziv=?");
		ps.setString(1, naziv);
		ResultSet rs = ps.executeQuery();
		if(!rs.next()) return -1;
		int rez=rs.getInt(1);
		rs.close();
		c.close();
		return rez;
		
	}
	
	public static void brisiPrevoznika(String naziv) throws Exception
	{
		Connection c = daoKonekcija.dajKonekciju();
		int idPrevoznika=dajidPrevoznika(naziv);
		if(idPrevoznika<0) throw new Exception("Nema prevoznika sa tim ID-em!");
		CallableStatement cStmt = c.prepareCall("{CALL deletePrevoznik(?)}"); 
		cStmt.setInt(1,idPrevoznika);
		cStmt.execute(); 
		System.out.println("Uspjesno"); 
		cStmt.close();
		c.close();
	}
	
	public static ListaPrevoznika dajImenaPrevoznika() throws SQLException {
		Connection c = daoKonekcija.dajKonekciju();
		ListaPrevoznika rez=new ListaPrevoznika();
		String iskaz = "SELECT Naziv FROM prevoznik";
		try {
			Statement stmt = c.createStatement();
			ResultSet rs=stmt.executeQuery(iskaz);
			while (rs.next()) {
		    	String naziv=rs.getString(1);
		        rez.getPrevoznici().add(new uPrevoznik(naziv)); 
		        }
			rs.close();
		    stmt.close();
		    c.close();
		    return rez;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			if(c!=null)c.close();
			e.printStackTrace();
		}
		return rez;
		
	}
}
